package com.fulihui.usercore.core.generator;

import com.fulihui.usercore.config.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;

/**
 * 昵称生成器
 *
 * @author Willard.Hu on 2016/8/20.
 */
@Component("nicknameGenerator")
public class NicknameGenerator implements IGenerator {
    /**
     * 昵称计数器，确保唯一性
     */
    private static final String NICKNAME_COUNTER_REDISKEY = "NICKNAME_COUNTER:";
    /**
     * 福礼惠默认昵称前缀
     */
    private static final String NICKNAME_PREFIX = "FLH";
    /**
     * 日期起始点
     */
    private final static long epoch = 1463108596098L;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 初始化redis计数器从 100000000 开始
     */
    @PostConstruct
    private void init() {

        if (redisUtil.get(NICKNAME_COUNTER_REDISKEY) == null) {
            redisUtil.set(NICKNAME_COUNTER_REDISKEY, "100000000");
        }

    }

    @Override
    public String generate() {

        // 起始时间到当前时间的分钟数作为随机因子, 用来减少全是1个数的出现情况
        long value = (System.currentTimeMillis() - epoch) / 60000
                + redisUtil.incr(NICKNAME_COUNTER_REDISKEY, 1);
        return NICKNAME_PREFIX + String.valueOf(value);

    }
}
